import http from '@ohos.net.http';
import { RequestOptions } from './RequestOptions';
import { ApiResult } from '../ApiResult/ApiResult';
import { StorageKeys } from '../../utils/StorageKeys';
import { BusinessError } from '@kit.BasicServicesKit';
import { StorageUtils } from '../../utils/StorageUtils';

/**
 * Http请求器
 */

export class HttpCore {
  /**
   * 发送请求
   * @param requestOption
   * @returns Promise
   */
  async request(requestOptions: RequestOptions): Promise<ApiResult<boolean>> {
    let p = new Promise<ApiResult<boolean>>(async (resolve, reject) => {
      // 每一个httpRequest对应一个HTTP请求任务，不可复用
      let httpRequest = http.createHttp();
      let baseurl = await getBaseUrl();
      console.log("-------" + baseurl + requestOptions.url);
      let promise = httpRequest.request(baseurl + requestOptions.url, {
        method: requestOptions.method,
        connectTimeout: 600000,
        readTimeout: 600000,
        header: {
          'Content-Type': 'application/json',
        },
        extraData: requestOptions.extraData
      });
      promise.then((data) => {
        console.log("------data" + JSON.stringify(data.result.toString()))
        let resultObj = JSON.parse(data.result.toString()) as ApiResult<boolean>;
        //如果业务码为20000 则返回ApiReslut
        if (resultObj.code == 20000) {
          resolve(resultObj);
        }

      }).catch((err: BusinessError) => {
        //这里做全局异常统一处理  根据Http状态码做出处理
        console.info('error:' + JSON.stringify(err));
        reject(err);
      }).finally(() => {
        httpRequest.destroy();
      });
    })
    return p;
  }
}

async function getBaseUrl(): Promise<string> {
  StorageUtils.context = AppStorage.Get("context")
  return new Promise<string>(async (resolve) => {
    try {
      const ip = await StorageUtils.get(StorageKeys.IP_KEY, '127.0.0.1', StorageKeys.APP_KEY);
      const post = await StorageUtils.get(StorageKeys.POST_KEY, '9090', StorageKeys.APP_KEY);
      const baseurl = "http://" + ip + ":" + post + "/"
      resolve(baseurl);
    } catch (err) {
      resolve(''); // Handle any errors by returning an empty string
    } finally {
    }
  });
}

export const httpCore = new HttpCore();
